package com.itheima.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 短信发送工具类
 *
 * @author Encounter
 */
@Data
@Slf4j
@AllArgsConstructor
public class SMSUtils
    {
        // 发送短信验证码 模板CODE "SMS_474565142"
        private String validateCode;
        // 体检预约成功通知 模板CODE "SMS_474640215"
        private String orderNotice;
        private String accessKeyId;
        private String accessKeySecret;
        // signName签名
        private String signName;
        
        /**
         * 发送短信
         *
         * @param templateCode 模板
         * @param phoneNumbers 手机号
         * @param map          参数
         */
        public boolean sendMessage(String templateCode, String phoneNumbers, Map<String, String> map)
            {
                DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
                IAcsClient client = new DefaultAcsClient(profile);
                
                SendSmsRequest request = new SendSmsRequest();
                request.setSysRegionId("cn-hangzhou");
                request.setPhoneNumbers(phoneNumbers);
                request.setSignName(signName);
                request.setTemplateCode(templateCode);
                if (map.get("code") != null)
                    {
                        request.setTemplateParam("{\"code\":\"" + map.get("code") + "\"}");
                    }
                else if (map.get("name") != null)
                    {
                        request.setTemplateParam("{\"name\":\"" + map.get("name") + "\"}");
                    }
                else
                    {
                        log.error("参数有误，请重新检查参数！！！");
                        return false;
                    }
                try
                    {
                        SendSmsResponse response = client.getAcsResponse(request);
                        if ("OK".equals(response.getCode()))
                            {
                                log.info("短信发送成功，RequestId：{}，Message：{}", response.getRequestId(), response.getMessage());
                                return true;
                            }
                        else
                            {
                                log.error("短信发送失败，Message：{}", response.getMessage());
                                return false;
                            }
                    }
                catch (ClientException e)
                    {
                        log.error("短信发送异常", e);
                        return false;
                    }
            }
        
    }